﻿using System.Collections.Generic;
using System.IO;
using System.Linq;

using EmbeddedSensorCloud.Log;
using EmbeddedSensorCloud.Command;
using System;

namespace EmbeddedSensorCloud.Console.Commands
{
    public class LogFileCommand : CommandBase
    {
        private readonly List<LogBase> loggers;

        public LogFileCommand(List<LogBase> loggers)
        {
            if (loggers == null)
            {
                throw new ArgumentException("List of loggers cannot be null");
            }

            this.loggers = loggers;
        }

        protected override void execute(string[] param)
        {
            if (param == null || param.Length == 0)
            {
                throw new ArgumentException("Arguments cannot be null or empty");
            }

            if (param[0] == "off")
            {
                int removed = this.loggers.RemoveAll(T => T is FileLog);
                if (removed == 0)
                {
                    base.RaiseLogged("No file logger currently on.");
                }
                else
                {
                    base.RaiseLogged("File logger off.");
                }
            }
            else if (param[0] == "on")
            {
                if (!this.loggers.Any(L => L is FileLog))
                {
                    try
                    {
                        File.WriteAllText(param[1], "");
                    }
                    catch
                    {
                        base.RaiseLogged("Invalid log path.");
                        return;
                    }

                    this.loggers.Add(new FileLog(param[1]));
                    base.RaiseLogged("File logger on.");
                }
                else
                {
                    base.RaiseLogged("File logger already on.");
                }
            }
        }

        public override string Description
        {
            get { return "Enable or disable file logging."; }
        }

        public override string Name
        {
            get { return "logfile"; }
        }

        public override string Syntax
        {
            get { return string.Format("{0} [on <filepath>] [off]", this.Name); }
        }

        public override string RequiredArgumentRegex
        {
            get { return "(on .+|off)"; }
        }
    }
}
